package de.Hijack.Giuliani;

import android.graphics.Point;

/**
 *
 * @author Bastian Hinterleitner
 */
public class Helper {
    
    /**
     * returns a Point snapped to a line starting at src and ending at dest
     * @param src the start of a line
     * @param dest the end of a line
     * @param p your position
     * @param dist the maximal distance at which you snap to the line
     * @return a point on the line or the position if its further away from the line than dist
     */
    public static Point snapTo(Point src, Point dest, Point p, float dist){
        double length = Math.cos(calcAngle(sub(dest,src), sub(p,src)))*dist(src,p);
        double multiplikator = length/dist(src,dest);
        Point snap = new Point();
        double xPlus = multiplikator*(dest.x-src.x);
        double yPlus = multiplikator*(dest.y-src.y);
        snap.x = (int)(src.x + xPlus);
        snap.y = (int)(src.y + yPlus);
        if(dist(p,snap)>dist){
            return p;
        }else{
            return snap;
        }
    }
    
    private static double dist(float x1, float y1, float x2, float y2){
        return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2));
    }
    
    private static double dist(Point p1, Point p2){
        return dist(p1.x,p1.y,p2.x,p2.y);
    }
    
    private static Point sub(Point p1, Point p2){
        return new Point(p1.x-p2.x,p1.y-p2.y);
    }
    
    private static float calcAngle(Point p0, Point p1){
        float x0 = (float)p0.x;
        float y0 = (float)p0.y;
        float x1 = (float)p1.x;
        float y1 = (float)p1.y;

        float op = x1*y0-x0*y1;
        float ip = x0*x1+y0*y1;   

        return (float)Math.toDegrees(Math.atan2(op,ip));
    }
}
